use sqlx::MySqlPool;
use std::io::{Error, ErrorKind};
use tklog::error;

#[derive(Clone, Debug)]
pub struct AccessCount<'a> {
    pub url: &'a str,
    pub article_id: i32,
    pub total_times: i32,
}

impl<'a> AccessCount<'a> {
    pub fn new(url: &'a str, article_id: i32, total_times: i32) -> Self {
        AccessCount {
            url,
            article_id,
            total_times,
        }
    }

    pub async fn update(&self, pool: &MySqlPool) -> Result<(), Error> {
        println!("execute update ---------------------{}", &self.total_times);
        let result_update = sqlx::query(
			r#"
			INSERT INTO access_count (url, article_id, total_times, create_by, create_on, modify_by, modify_on)
			VALUES (?, ?, ?, 'Scheduelr', NOW(), 'Scheduelr', NOW())
			ON DUPLICATE KEY UPDATE
				total_times = total_times + VALUES(total_times),
				modify_by = 'Scheduelr',
				modify_on = now(),
				create_by = 'Scheduelr',
				create_on = now()"#
		)
		.bind(self.url)
		.bind(self.article_id)
		.bind(self.total_times)
		.execute(pool)
		.await;
        match result_update {
            Ok(_) => Ok(()),
            Err(e) => {
                error!(e.to_string());
                Err(Error::new(ErrorKind::Other, e.to_string()))
            }
        }
    }
}
